<?php
declare (strict_types = 1);

namespace app\admin\controller\delivery\channel;

use app\admin\traits\Actions;
use think\annotation\route\Group;
use think\annotation\route\Route;

#[Group("delivery/channel-staff")]
class Staff extends ChannelBase
{
    private $type='';

    use Actions{
        add as private _add;
        edit as private _edit;
    }

    protected function _initialize()
    {
        parent::_initialize();
        $this->type = $this->request->get('type','Driver');
        $modelname='app\\common\\model\\delivery\\'.$this->type;
        $this->model = new $modelname();
    }

    #[Route('GET,JSON','index')]
    public function index()
    {
        if (false === $this->request->isAjax()) {
            return $this->fetch();
        }
        if($this->request->post('selectpage')){
            $where=[];
            $where[]=['channel_id','=',$this->channel->id];
            return $this->selectpage($where);
        }
        $this->relationField=['user'];
        $where=[];
        $where[]=['channel_id','=',$this->channel->id];
        [$where, $order, $limit, $with] = $this->buildparams($where);
        $list = $this->model
            ->with($with)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    #[Route('GET,POST','add')]
    public function add()
    {
        $this->check();
        return $this->_add();
    }

    #[Route('GET,POST','edit')]
    public function edit()
    {
        $this->check();
        return $this->_edit();
    }

    private function check()
    {
        if($this->request->isPost()){
            $staff=$this->model->where(function ($query){
                $user_id=$this->request->post('row.user_id');
                $query->where('user_id',$user_id);
                $query->where('channel_id',$this->channel->id);
                $id=$this->request->post('row.id');
                if($id){
                    $query->where('id','<>',$id);
                }
            })->find();
            if($staff){
                $title='';
                if($this->type=='Driver'){
                    $title='司机';
                }
                if($this->type=='Seller'){
                    $title='销售';
                }
                $this->error('该用户已经绑定了别的'.$title);
            }
            $this->postParams['channel_id']=$this->channel->id;
        }
    }
}